package com.zhq.zhq_blog.module.blog.fragment

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import com.jeremyliao.liveeventbus.LiveEventBus
import com.kingja.loadsir.core.LoadService
import com.kingja.loadsir.core.LoadSir
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener
import com.zhq.zhq_blog.R
import com.zhq.zhq_blog.base.BaseVMFragment
import com.zhq.zhq_blog.callback.LoadingCallback
import com.zhq.zhq_blog.databinding.FragmentBlogListBinding
import com.zhq.zhq_blog.module.blog.activity.BlogDetailActivity
import com.zhq.zhq_blog.module.blog.adapter.BlogAdapter
import com.zhq.zhq_blog.module.blog.viewmodel.BlogListFragmentViewModel
import com.zhq.zhq_blog.module.bus.UpdateBlogEvent
import com.zhq.zhq_blog.module.bus.UpdateUserInfoEvent
import com.zhq.zhq_blog.util.CommonLinearItemDecoration
import com.zhq.zhq_blog.util.PageUtil
import com.zhq.zhq_blog.util.RefreshUtil
import com.zhq.zhq_blog.util.zhq.ZHQUtil
import com.zhq.zhq_blog.util.zhq.toast

/**
 * 博客列表
 */
class BlogListFragment : BaseVMFragment<BlogListFragmentViewModel>() {
    lateinit var mViewBinding: FragmentBlogListBinding
    val adapter: BlogAdapter by lazy { BlogAdapter(null) }
    private lateinit var loadService: LoadService<Any>

    override fun createView(inflater: LayoutInflater?, container: ViewGroup?): View {
        mViewBinding = FragmentBlogListBinding.inflate(inflater!!, container, false)
        return mViewBinding.root
    }

    override fun onLazyLoad() {
        getPageList(true)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        loadService = LoadSir.getDefault().register(
            mViewBinding.smartRefreshLayout
        ) {
            loadService.showCallback(LoadingCallback::class.java)
            getPageList(true)
        }
        loadService.showCallback(LoadingCallback::class.java)
        mViewBinding.recyclerView.layoutManager = LinearLayoutManager(requireActivity())
        mViewBinding.recyclerView.addItemDecoration(
            CommonLinearItemDecoration(
                dividerColor = requireContext().getColor(R.color.common_theme),
                dividerHeight = ZHQUtil.dp2px(0.5f)
            )
        )
        mViewBinding.recyclerView.adapter = adapter
        adapter.addChildClickViewIds(R.id.ll_collect)
        adapter.addChildClickViewIds(R.id.ll_comment)
        adapter.addChildClickViewIds(R.id.ll_praise)
        adapter.setOnItemClickListener { _, _, position ->
            BlogDetailActivity.startActivity(
                requireContext(),
                intentBean = BlogDetailActivity.Companion.IntentBean(this.adapter.getItem(position).id)
            )
//            BlogDetailActivity.startActivityForTransition(
//                requireActivity(),
//                intentBean = BlogDetailActivity.Companion.IntentBean(this.adapter.getItem(position).id),
//                view.findViewById(R.id.tv_title),
//                view.findViewById(R.id.tv_username),
//                view.findViewById(R.id.tv_content)
//            )
        }
        adapter.setOnItemChildClickListener { _, _, position ->
            if (view.id == R.id.ll_collect) {
                val item = this.adapter.getItem(position)
                if (item.isMyCollected == 0) {
                    netCollect(this.adapter.getItem(position).id, true)
                } else {
                    netCollect(this.adapter.getItem(position).id, false)
                }

            } else if (view.id == R.id.ll_praise) {
                val item = this.adapter.getItem(position)
                if (item.isMyPraised == 0) {
                    netPraise(this.adapter.getItem(position).id, true)
                } else {
                    netPraise(this.adapter.getItem(position).id, false)
                }
            } else if (view.id == R.id.ll_comment) {
                BlogDetailActivity.startActivityComment(
                    requireContext(),
                    intentBean = BlogDetailActivity.Companion.IntentBean(this.adapter.getItem(position).id)
                )
            }
        }
        mViewBinding.smartRefreshLayout.setEnableLoadMore(true)
        mViewBinding.smartRefreshLayout.setOnRefreshLoadMoreListener(object :
            OnRefreshLoadMoreListener {
            override fun onRefresh(refreshLayout: RefreshLayout) {
                getPageList(true)
            }

            override fun onLoadMore(refreshLayout: RefreshLayout) {
                getPageList(false)
            }

        })
        initBus()
    }

    private fun initBus() {
        //监听事件总线的消息
        LiveEventBus
            .get(UpdateBlogEvent::class.java)
            .observe(this) {
                getPageList(true)
            }
        LiveEventBus
            .get(UpdateUserInfoEvent::class.java)
            .observe(this) {
                getPageList(true)
            }
    }

    fun getPageList(isRefresh: Boolean) {
        mViewModel.getPageList(PageUtil.getNextServerPageBean(isRefresh, adapter.data.size))
            .observe(viewLifecycleOwner) {
                RefreshUtil.changeRefreshViewStatus(
                    mViewBinding.smartRefreshLayout,
                    it?.data?.dataList?.size ?: 0,
                )
                if (it.isServerResultOK()) {
                    if (isRefresh) {
                        adapter.setNewInstance(it.data?.dataList?.toMutableList())
                    } else {
                        adapter.addData(it.data?.dataList!!.toMutableList())
                    }
                } else {
                    toast(it.msg)
                }

                RefreshUtil.changeLoadServiceStatus(it.code, loadService, adapter.data.size)
            }
        mViewModel.livedataComplete.observe(viewLifecycleOwner) {
            mViewBinding.smartRefreshLayout.finishRefresh()
            mViewBinding.smartRefreshLayout.finishLoadMore()
        }
    }

    private fun netCollect(blogId: Int, isCollect: Boolean) {
        var type = 1
        if (!isCollect) {
            type = 2
        }
        mViewModel.collect(blogId, type)
            .observe(viewLifecycleOwner) {
                if (it.isServerResultOK()) {
                    adapter.data.forEachIndexed { index, data ->
                        if (data.id == blogId) {
                            if (isCollect) {
                                adapter.data[index].isMyCollected = 1
                                adapter.data[index].collectCount++
                                Log.d(
                                    "BlogListFragment",
                                    "net_collect: 收藏成功，count=" + adapter.data[index].collectCount
                                )
                                toast("收藏成功")
                            } else {
                                adapter.data[index].isMyCollected = 0
                                adapter.data[index].collectCount--
                                Log.d(
                                    "BlogListFragment",
                                    "net_collect: 取消收藏成功，count=" + adapter.data[index].collectCount
                                )
                                toast("已取消收藏")
                            }
                            adapter.notifyItemChanged(index)
                        }
                    }
                } else {
                    toast(it.msg)
                }

            }
    }

    private fun netPraise(blogId: Int, isPraise: Boolean) {
        var type = 1
        if (!isPraise) {
            type = 2
        }
        mViewModel.praise(blogId, type)
            .observe(viewLifecycleOwner) {
                if (it.isServerResultOK()) {
                    adapter.data.forEachIndexed { index, data ->
                        if (data.id == blogId) {
                            if (isPraise) {
                                adapter.data[index].isMyPraised = 1
                                adapter.data[index].praiseCount++
                                Log.d(
                                    "BlogListFragment",
                                    "net_praise: 点赞成功，count=" + adapter.data[index].praiseCount
                                )
                                toast("点赞成功")
                            } else {
                                adapter.data[index].isMyPraised = 0
                                adapter.data[index].praiseCount--
                                Log.d(
                                    "BlogListFragment",
                                    "net_praise: 取消点赞成功，count=" + adapter.data[index].praiseCount
                                )
                                toast("已取消点赞")
                            }
                            adapter.notifyItemChanged(index)
                        }
                    }
                } else {
                    toast(it.msg)
                }

            }
    }
}